package com.heba.fragment.mine;

import android.os.Bundle;
import androidx.annotation.Nullable;
 import androidx.recyclerview.widget.GridLayoutManager;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.diary.ItemDiaryDetailObject;
import com.heba.bean.diary.ItemDiaryImageObject;
import com.heba.config.CommonConfig;
import com.heba.decoration.GridSpaceDecoration;
import com.heba.fragment.LazyFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.user.UserDiaryListActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 日记页面
 * <p>
 * Created by jason on 2020/1/2.
 */
public class MineDiaryFragment extends LazyFragment {

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;

    private List<ItemDiaryDetailObject> list;

    private String uID;  //需要获取数据的用户的ID
    private String url = CommonConfig.DIARY_USER_LIST_URL;  //获取api数据

    private String hashTagID;
    private TextView alertLB;

    /**
     * 实例化fragment
     * 接收参数
     *
     * @param UID
     * @return
     */
    public static MineDiaryFragment newInstance(String UID) {
        MineDiaryFragment fragment = new MineDiaryFragment();
        Bundle bundle = new Bundle();
        bundle.putString(CommonConfig.USER_ID, UID);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 实例化fragment
     * 接收参数
     *
     * @param UID
     * @param url
     * @return
     */
    public static MineDiaryFragment newInstance(String UID, String url) {
        MineDiaryFragment fragment = new MineDiaryFragment();
        Bundle bundle = new Bundle();
        bundle.putString(CommonConfig.HASHTAG_ID, UID);
        bundle.putString(CommonConfig.URL, url);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 取出参数
     */
    private void parseArgument() {
        Bundle bundle = getArguments();
        uID = bundle.getString(CommonConfig.USER_ID, "");
        hashTagID = bundle.getString(CommonConfig.HASHTAG_ID, "");
        url = bundle.getString(CommonConfig.URL, CommonConfig.DIARY_USER_LIST_URL);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void lazyLoad() {
        getDiaryListData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_mine_diary_recyclerview, container, false);
        parseArgument();
        initView(view);
        return view;
    }

    /**
     * @param view
     */
    private void initView(View view) {
        refreshLayout = view.findViewById(R.id.refreshLayout);
        recyclerView = view.findViewById(R.id.recyclerView);
        alertLB = view.findViewById(R.id.alertLB);
        alertLB.setText(R.string.no_post);
        //设置显示图片宽高
        final int imageWidth = (DensityUtils.getWidth(getActivity()) - DensityUtils.dip2px(getActivity(), 2)) / 3;
        list = new ArrayList<>();

        recycleAdapter = new QuickAdapter<ItemDiaryDetailObject>(list) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_image_row;
            }

            @Override
            public void convert(VH holder, ItemDiaryDetailObject data, int position) {
                ImageView iv_play = holder.getView(R.id.iv_play);
                ImageView iv_muti = holder.getView(R.id.iv_muti);
                ImageView imageView = holder.getView(R.id.imageView);
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(imageWidth, imageWidth);
                holder.itemView.setLayoutParams(params);
                iv_muti.setVisibility(View.GONE);

                /**
                 * 显示照片
                 */
                iv_play.setVisibility(View.GONE);
                if (!data.getImageList().isEmpty() && data.getImageList().size() > 0) {
                    if (data.getImageList().size() > 1)
                        iv_muti.setVisibility(View.VISIBLE);
                    ItemDiaryImageObject object = data.getImageList().get(0);
                    GlideUtil.loadImageWithDefaultPlaceHolder(getActivity(), object.getImageUrl(), imageView);
                    if (object.getType() == 1) {
                        iv_play.setVisibility(View.VISIBLE);
                    }
                } else {
                    Glide.with(getActivity()).load(R.drawable.btn_upload_image).into(imageView);
                }

                /**
                 * 进入日记列表页
                 */
                holder.itemView.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString(CommonConfig.HASHTAG_ID, hashTagID);
                    bundle.putString(CommonConfig.USER_ID, uID);
                    bundle.putString(CommonConfig.USER_NAME, data.getAccount());
                    bundle.putSerializable(CommonConfig.DIARY_LIST, (Serializable) list);
                    bundle.putInt(CommonConfig.DIARY_POSITION, position);
                    bundle.putString(CommonConfig.URL, url);
                    openActivity(UserDiaryListActivity.class, bundle);
                });
            }
        };

        /**
         * 设置layoutManager布局
         */
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        /**
         * 设置item间隔
         */
        recyclerView.addItemDecoration(new GridSpaceDecoration(getContext(), 3, list.size()));
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            Page = 1;
            isRefreshFromTop = true;
            getDiaryListData();
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            Page++;
            isRefreshFromTop = false;
            getDiaryListData();
        });
    }

    /**
     * 获取日记列表数据
     */
    private void getDiaryListData() {
        if (firstRefresh) {
            progressDialog.show();
            firstRefresh = false;
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", 18);
        params.put("UID", uID);
        params.put("HashtagID", hashTagID);
        client.get(Cfg.BaseUrl + url, params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);

                        /**
                         * 下拉刷新处理
                         */
                        if (isRefreshFromTop) {
                            isRefreshFromTop = false;
                            refreshLayout.setNoMoreData(false);
                            list.clear();
                        }

                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemDiaryDetailObject> diaryDetailObjects = new Gson().fromJson(array.toString(), new TypeToken<List<ItemDiaryDetailObject>>() {
                                }.getType());
                                list.addAll(list.size(), diaryDetailObjects);
                                alertLB.setVisibility(View.GONE);
                            } else {
                                //无数据
                                refreshLayout.finishLoadMoreWithNoMoreData();
                                alertLB.setVisibility(View.VISIBLE);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //刷新数据
                        recycleAdapter.notifyDataSetChanged();
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);
                    }

                });
    }

}
